package com.guchenbo.bigdata.livy;

import org.apache.livy.Job;
import org.apache.livy.JobContext;

import java.util.ArrayList;
import java.util.List;

/**
 * @author guchenbo
 */
public class Pi implements Job<Double> {

    private int count;

    public Pi(int count) {
        this.count = count;
    }

    @Override
    public Double call(JobContext jobContext) throws Exception {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            list.add(i + 1);
        }
        return 4.0 * jobContext.sc().parallelize(list).map(r -> {
            double x = Math.random();
            double y = Math.random();
            return (x * x + y * y < 1) ? 1 : 0;
        }).reduce((r1, r2) -> r1 + r2) / count;
    }
}
